<template>
  <div id="rolePage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-button type="primary" @click="handleCreate">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'updatedBy'">
            {{ record.updatedBy?.username ?? "" }}
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleView(record)">查看</a-button>
            <a-button @click="handleAssignMenu(record)">分配菜單</a-button>
            <a-button @click="handleAssignPermission(record)"
              >分配權限</a-button
            >
            <a-button @click="handleEdit(record)">修改</a-button>
            <a-button danger @click="handleDelete(record)">刪除</a-button>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 新建模態框 -->
    <a-modal v-model:open="showModalCreate" title="新建角色" :footer="null">
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯角色
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        :formData="editFormData"
        @submit="handleEditSubmit"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message, Modal } from "ant-design-vue";
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { roleApi } from "@/api";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  filterFields,
  getCreateFieldConfig,
  getEditFieldConfig,
} from "@/models/role";
import TableFilter from "@/components/TableFilter.vue";
import { useRouter, useRoute } from "vue-router";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";

/*******頁面狀態與配置 *****************************/
const breadcrumbItems = [{ url: "", name: "角色管理" }];
const columns = tableColumns;
const filterConfig = filterFields;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// 分頁配置
const pagination = createPagination();

// 數據
const tableData = ref([]);
const editRecordId = ref<number>(0); // 當前編輯的用戶ID
const editFormData = reactive<any>({}); // 當前編輯的用戶數據

/******* 數據獲取與初始化 *****************************/

// 獲取數據
const fetchData = async (params?: any) => {
  loading.value = true;
  try {
    const {
      data: { list, page, limit, total },
    } = await roleApi.getRoleList(params);
    tableData.value = list || [];
    // 更新分頁參數
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取角色列表失敗", error);
  } finally {
    loading.value = false;
  }
};

/******* 監聽路由變化,更新列表數據 *****************************/
watchRouteQuery(fetchData);

/******* 用戶操作處理 *****************************/
// 搜索
const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 新建
const showModalCreate = ref(false);

const handleCreate = () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = getCreateFieldConfig();
  }
  showModalCreate.value = true;
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  // 處理表單提交邏輯
  try {
    await roleApi.createRole(data);
    message.success("創建角色成功");
    showModalCreate.value = false;
    // 調用子組件的 resetForm 方法
    createFormRef.value?.resetForm();
    fetchData(route.query);
  } catch (error) {
    console.error("創建角色失敗", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 修改
const showModalEdit = ref(false);

const handleEdit = (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  Object.assign(editFormData, record); // 使用 Object.assign 更新 reactive 對象
  showModalEdit.value = true;
};
// 處理編輯完成
const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    await roleApi.updateRole(editRecordId.value, data);
    message.success("修改角色成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改角色失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

// 查看
const handleView = (record: any) => {
  router.push({ name: "RoleDetail", params: { id: record.id } });
};

// 處理分配菜單操作
const handleAssignMenu = (record: any) => {
  router.push({ name: "AssignMenu", params: { id: record.id } });
};
// 處理分配菜單操作
const handleAssignPermission = (record: any) => {
  router.push({ name: "AssignPermission", params: { id: record.id } });
};

// 處理刪除操作
const handleDelete = async (record: any) => {
  // 顯示確認對話框
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除用戶 ${record.username} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      // 用戶確認刪除
      try {
        await roleApi.deleteRole(record.id);
        message.success("刪除角色成功");
        fetchData();
      } catch (error) {
        console.error("刪除角色失敗", error);
      }
    },
  });
};
</script>

<style scoped></style>
